package net.ghsoft
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.describeType;
	
	import mx.collections.ArrayCollection;
	
	import net.ghsoft.AppGlobal;
	
	import spark.components.Button;

	public class CtrlGlobal
	{
		
		private static var _XMLLanguage:XML;
		private static var _ArrCtrl:ArrayCollection = new ArrayCollection();
		
		public static function InitLanguage(strLanguage:String = "English"):void
		{
			var strURL:String = AppGlobal.WebURL;
			var strTableURL:String = strURL.replace("Weather.swf", "Language/") + strLanguage + ".xml";
			
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,onLoadComplete,false,0,true);
			
			var request:URLRequest = new URLRequest(strTableURL);
			loader.load(request);
			
			function onLoadComplete(event:Event):void
			{
				var loader:URLLoader = event.target as URLLoader;
				_XMLLanguage = new XML(loader.data);
				if(_ArrCtrl.length > 0)
				{
					for each(var disp:DisplayObject in _ArrCtrl)
					{
						LanguageObject(disp);
					}
//					_ArrCtrl.removeAll();
				}
			}
		}

		public static function LanguageObject(disp:DisplayObject):void
		{
			if(_XMLLanguage != null)
			{
				var instanceInfo:XML = describeType(disp);//通过反射机制取出当前MXML中的信息 
				LanguageCtrl(disp, instanceInfo, "Button", "label");
				LanguageCtrl(disp, instanceInfo, "Label", "text");
				LanguageCtrl(disp, instanceInfo, "MyDropDownList", "dropDownValue");
				LanguageCtrl(disp, instanceInfo, "MySelectBox", "selectDataValue");
			}
			if(_ArrCtrl.getItemIndex(disp) < 0)
			{
				_ArrCtrl.addItem(disp);
			}
		}
		
		private static function LanguageCtrl(disp:DisplayObject, instanceInfo:XML, strCtrlName:String, strCtrlPro:String):void
		{
			var properties:XMLList = instanceInfo..accessor.(@type.search(new RegExp("::" + strCtrlName + "$"))>-1);
			for each(var propertyInfo:XML in properties)
			{         
				var propertyName:String = propertyInfo.@name;//此处取出的为textinput的id  
				var doTemp:DisplayObject = disp[propertyName] as DisplayObject;
				
				if(doTemp != null && doTemp.hasOwnProperty(strCtrlPro))
				{
					var strTemp:String = doTemp[strCtrlPro].toString();
					if(_XMLLanguage.hasOwnProperty(strTemp))
					{
						doTemp["name"] = strTemp
						doTemp[strCtrlPro] = _XMLLanguage[strTemp].toString();
					}
					else
					{
						strTemp = doTemp["name"].toString();
						if(_XMLLanguage.hasOwnProperty(strTemp))
						{
							doTemp[strCtrlPro] = _XMLLanguage[strTemp].toString();
						}
					}
				}
			}
		}		
	}
}